﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NetSDKCS;
using CaseManagerLibrary.Http;
using PSDLib.Models;
using CaseManagerLibrary.Models;
using Newtonsoft.Json;
using PSDLib.Download;

namespace PSDManager.SystemSettings
{
    public partial class ChannelSettingPanel : UserControl, ISettingPanel
    {
        public ManagerHelper ManagerHelper { get; set; }

        private List<string> rooms = new List<string>();
        private Dictionary<string, List<PSDLib.Download.ChannelInfo>> channelIds = new Dictionary<string, List<PSDLib.Download.ChannelInfo>>();

        public string DownloadServerIP { get; set; }
        public ushort DownloadServerPort { get; set; }
        public string DownloadServerUser { get; set; }

        public string DownloadServerPassword { get; set; }

        public ChannelSettingPanel()
        {
            InitializeComponent();

            this.lvwServer.SelectedIndexChanged += LvwServer_SelectedIndexChanged;
        }

        private void LvwServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwServer.SelectedItems.Count > 0)
            {
                var server = this.lvwServer.SelectedItems[0].Tag as dl_server_config;

                var result_ch = HttpHelper.Get<HResult<List<dl_room_config>>>(AppSettings.Setting.API.GetRoomConfigList + "?serverId=" + server.id);

                this.lvwChannel.Items.Clear();

                if (result_ch.success)
                {

                    foreach (var item in result_ch.data)
                    {
                        this.lvwChannel.Items.Add(new ListViewItem(new string[] {
                        (this.lvwChannel.Items.Count+1).ToString(),
                        item.room_num,
                        item.channel_name,
                        item.channel_id.ToString()
                    })).Tag = item.id;
                    }
                }
            }
        }

        public void ApplySettings()
        {
            SaveSettings();
        }

        public void LoadSettings()
        {
            //this.txtDownloadServerIP.Text = AppSettings.Setting.DownloadServerIP;
            //this.txtDownloadServerPort.Text = AppSettings.Setting.DownloadServerPort.ToString();
            //this.txtDownloadServerUser.Text = AppSettings.Setting.DownloadServerUser;
            //this.txtDownloadServerPassword.Text = AppSettings.Setting.DownloadServerPassword;

            var result_server = HttpHelper.Get<HResult<List<dl_server_config>>>(AppSettings.Setting.API.GetDownloadServerConfig);
            this.lvwServer.Items.Clear();
            if (result_server.success)
            {
                if (ManagerHelper != null)
                {
                    ManagerHelper.DownloadServerList = result_server.data;
                }

                foreach (var server in result_server.data)
                {
                    this.lvwServer.Items.Add(new ListViewItem(new string[] {
                        (this.lvwServer.Items.Count+1).ToString(),
                        server.storage_server_name,
                        server.storage_server_type,
                        server.storage_server_ip,
                        server.storage_server_port.ToString(),
                        server.storage_server_user,
                        server.stream_type==0 ? "主码流":"副码流"
                    })).Tag = server;
                }

                if (lvwServer.Items.Count > 0)
                {
                    lvwServer.Items[0].Selected = true;
                }
            }
        }

        public void SaveSettings()
        {
            //AppSettings.Setting.DownloadServerIP = this.txtDownloadServerIP.Text.Trim();
            //AppSettings.Setting.DownloadServerPort = Convert.ToUInt16(this.txtDownloadServerPort.Text.Trim());
            //AppSettings.Setting.DownloadServerUser = this.txtDownloadServerUser.Text.Trim();
            //AppSettings.Setting.DownloadServerPassword = this.txtDownloadServerPassword.Text.Trim();
        }

        private void btnAddChannel_Click(object sender, EventArgs e)
        {
            if (lvwServer.SelectedItems.Count > 0)
            {
                var server = (lvwServer.SelectedItems[0].Tag as dl_server_config);

                GetRooms();
                GetChannels(server);

                FrmChannel frm = new FrmChannel();
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.SetRooms(rooms);
                if (channelIds.ContainsKey(server.id))
                {
                    frm.SetChannels(channelIds[server.id]);
                }

                if (frm.ShowDialog() == DialogResult.OK && frm.ChannelSetting != null)
                {
                    frm.ChannelSetting.server_id = server.id;

                    string room = "";

                    foreach (ListViewItem item in this.lvwChannel.Items)
                    {
                        if (item.SubItems[3].Text == frm.ChannelSetting.channel_id.ToString())
                        {
                            room = item.SubItems[1].Text;
                            break;
                        }
                    }

                    if (string.IsNullOrEmpty(room))
                    {
                        var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.AddRoomConfig, JsonConvert.SerializeObject(frm.ChannelSetting));

                        if (result.success)
                        {

                            this.lvwChannel.Items.Add(new ListViewItem(new string[] {
                                (this.lvwChannel.Items.Count+1).ToString(),
                                frm.ChannelSetting.room_num,
                                frm.ChannelSetting.channel_name,
                                frm.ChannelSetting.channel_id.ToString()
                            })).Tag = frm.ChannelSetting.id;
                        }
                    }
                    else
                    {
                        MessageBox.Show("通道" + frm.ChannelSetting.channel_id + "已被" + room + "使用");
                    }
                }
            }
        }

        private void btnEditChannel_Click(object sender, EventArgs e)
        {
            if (this.lvwServer.SelectedItems.Count > 0 && this.lvwChannel.SelectedItems.Count > 0)
            {
                var server = (lvwServer.SelectedItems[0].Tag as dl_server_config);

                string id = this.lvwChannel.SelectedItems[0].Tag.ToString();
                string room = this.lvwChannel.SelectedItems[0].SubItems[1].Text;
                string channelName = this.lvwChannel.SelectedItems[0].SubItems[2].Text;
                string channelId = this.lvwChannel.SelectedItems[0].SubItems[3].Text;

                GetRooms();
                GetChannels(server);

                FrmChannel frm = new FrmChannel();
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.SetRooms(rooms);
                if (channelIds.ContainsKey(server.id))
                {
                    frm.SetChannels(channelIds[server.id]);
                }
                frm.SetChannelSetting(id, room, channelName, channelId);

                if (frm.ShowDialog() == DialogResult.OK && frm.ChannelSetting != null)
                {
                    frm.ChannelSetting.server_id = server.id;

                    var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.UpdateRoomConfig, JsonConvert.SerializeObject(frm.ChannelSetting));

                    if (result.success)
                    {
                        this.lvwChannel.SelectedItems[0].SubItems[1].Text = frm.ChannelSetting.room_num;
                        this.lvwChannel.SelectedItems[0].SubItems[2].Text = frm.ChannelSetting.channel_name;
                        this.lvwChannel.SelectedItems[0].SubItems[3].Text = frm.ChannelSetting.channel_id.ToString();
                    }
                }
            }
        }

        private void btnDelChannel_Click(object sender, EventArgs e)
        {
            if (this.lvwChannel.SelectedItems.Count > 0)
            {
                var result = HttpHelper.Post<HResult>(
                    AppSettings.Setting.API.DeleteRoomConfig,
                    new Dictionary<string, string> {
                        { "id", this.lvwChannel.SelectedItems[0].Tag.ToString() }
                    });

                if (result.success)
                {
                    this.lvwChannel.SelectedItems[0].Remove();
                }
            }
        }

        private void GetRooms()
        {
            if (rooms.Count == 0)
            {
                var result = HttpHelper.Get<HResult<List<rm_room_info>>>(AppSettings.Setting.API.GetFreeRoom);

                if (result.success)
                {
                    foreach (var room in result.data)
                    {
                        rooms.Add(room.room_number);
                    }
                }
            }
        }

        private void GetChannels(dl_server_config server)
        {
            List<PSDLib.Download.ChannelInfo> ch = null;

            if (channelIds.ContainsKey(server.id))
            {
                ch = channelIds[server.id];
            }

            if (ch == null)
            {
                IDownloadServer dServer = DownloadServerFactory.Create(server.storage_server_type);

                dServer.ServerIP = server.storage_server_ip;
                dServer.ServerPort = server.storage_server_port;
                dServer.ServerUser = server.storage_server_user;
                dServer.ServerPassword = server.storage_server_password;

                if (dServer.Init())
                {
                    if (dServer.Login())
                    {
                        ch = dServer.GetChannelList();

                        channelIds.Add(server.id, ch);
                    }

                    dServer.Logout();
                }
                dServer.Cleanup();
            }
        }

        private void btnAddServer_Click(object sender, EventArgs e)
        {
            FrmDownloadServer frm = new FrmDownloadServer();
            frm.StartPosition = FormStartPosition.CenterParent;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.ServerConfig != null)
                {
                    var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.AddDownloadServerConfig, JsonConvert.SerializeObject(frm.ServerConfig));

                    if (result.success)
                    {
                        if (ManagerHelper != null)
                        {
                            ManagerHelper.DownloadServerList.Add(frm.ServerConfig);
                        }

                        lvwServer.Items.Add(new ListViewItem(new string[] {
                            (this.lvwServer.Items.Count+1).ToString(),
                            frm.ServerConfig.storage_server_name,
                            frm.ServerConfig.storage_server_type,
                            frm.ServerConfig.storage_server_ip,
                            frm.ServerConfig.storage_server_port.ToString(),
                            frm.ServerConfig.storage_server_user,
                            frm.ServerConfig.stream_type == 0 ? "主码流" : "副码流"
                        })).Tag = frm.ServerConfig;
                    }
                }
            }
        }

        private void btnEditServer_Click(object sender, EventArgs e)
        {
            if (this.lvwServer.SelectedItems.Count > 0)
            {
                FrmDownloadServer frm = new FrmDownloadServer();
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.SetServerConfig(this.lvwServer.SelectedItems[0].Tag as dl_server_config);

                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (frm.ServerConfig != null)
                    {
                        var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.UpdateDownloadServerConfig, JsonConvert.SerializeObject(frm.ServerConfig));

                        if (result.success)
                        {
                            if (ManagerHelper != null)
                            {
                                var server = ManagerHelper.DownloadServerList.Where(t => t.id == frm.ServerConfig.id).FirstOrDefault();
                                if (server != null)
                                {
                                    ManagerHelper.DownloadServerList.Remove(server);
                                }
                                ManagerHelper.DownloadServerList.Add(frm.ServerConfig);
                            }
                            lvwServer.SelectedItems[0].SubItems[1].Text = frm.ServerConfig.storage_server_name;
                            lvwServer.SelectedItems[0].SubItems[2].Text = frm.ServerConfig.storage_server_type;
                            lvwServer.SelectedItems[0].SubItems[3].Text = frm.ServerConfig.storage_server_ip;
                            lvwServer.SelectedItems[0].SubItems[4].Text = frm.ServerConfig.storage_server_port.ToString();
                            lvwServer.SelectedItems[0].SubItems[5].Text = frm.ServerConfig.storage_server_user;
                            lvwServer.SelectedItems[0].SubItems[6].Text = (frm.ServerConfig.stream_type == 0 ? "主码流" : "副码流");
                            lvwServer.SelectedItems[0].Tag = frm.ServerConfig;
                        }
                    }
                }
            }
        }

        private void btnDelServer_Click(object sender, EventArgs e)
        {
            if (this.lvwServer.SelectedItems.Count > 0)
            {
                var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.DeleteDownloadServerConfig,
                    new Dictionary<string, string> {
                        {"id", (lvwServer.SelectedItems[0].Tag as dl_server_config).id }
                    });

                if (result.success)
                {
                    var server = ManagerHelper.DownloadServerList.Where(t => t.id == (lvwServer.SelectedItems[0].Tag as dl_server_config).id).FirstOrDefault();
                    if (server != null)
                    {
                        ManagerHelper.DownloadServerList.Remove(server);
                    }

                    lvwServer.SelectedItems[0].Remove();
                }
            }
        }
    }
}
